define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function() {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'leader_approach/index' + location.search,
                    add_url: 'leader_approach/add',
                    edit_url: 'leader_approach/edit',
                    del_url: 'leader_approach/del',
                    multi_url: 'leader_approach/multi',
                    table: 'leader_approach',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                singleSelect: true,
                detailView: true,
                toolbar: "#toolbar",

                columns: [
                    [
                        { checkbox: true },
                        // {field: '', title: __('序号'),operate:false,table: table,width:'50px',formatter:Table.api.formatter.natureorder},
                        { field: 'number', title: __('编号'),width:'50px'},
                        // {field: 'leader_ids', title: __('Leader_ids')},
                        { field: 'out_date', title: __('Out_date')},
                        { field: 'leader_names', title: __('Leader_names'),width:'200px'},
                        { field: 'out_city', title: __('Out_city'),width:'150px' },
                        // {field: 'create_time', title: __('Create_time'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        // {field: 'update_time', title: __('Update_time'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        { field: 'operate', title: __('Operate'),width:'250px',table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate }
                    ]
                ],
                onExpandRow: function(index, row, $detail) {
                    // console.log($detail);
                    InitSubTable(index, row, $detail);
                }
            });

            // 为表格绑定事件

            InitSubTable = function(index, row, $detail) {

                // console.log(row.status+"@@@@@@@@@@");
                var html = '';
                html += '<table class="table table-striped table-bordered " style="width:100%" >';
                html += '<tr>';
                html += '<th  style="text-align:center">序号</th>'
                html += '<th  style="text-align:center">拜访企业</th>'
                html += '<th  style="text-align:center">需推进事项</th>'
                html += '<th  style="text-align:center">责任单位</th>'
                html += '<th  style="text-align:center">工作进展情况</th>'
                html += '<th  style="text-align:center">存在问题</th>'
                html += '<th  style="text-align:center">下步计划</th>'
                html += '<th  style="text-align:center">操作</th>'
                html += '</tr>';
                var numArr = Controller.api.mergeCells(row.contents,'company');
                console.log(row.contents+"@@@@@@@@@@");
                for(var i=0;i<row.contents.length;i++) {
                    var item = row.contents[i];
                    // console.log(value.company)

                    if(item.status==0)
                    {
                        html += '<tr data-index='+i+' >';
                        let it = numArr.find((v)=>{
                            return v.index == i
                        })
                        let inx = numArr.findIndex((v)=>{
                            return v.index == i
                        })
                        if(it)
                        {
                            html += '<td rowspan="'+it.number+'" style="vertical-align:middle;text-align:center;">' + (inx+1) + '</td>'
                            html += '<td rowspan="'+it.number+'" style="vertical-align:middle;">' + item.company + '</td>'
                        }
                        html += '<td>' + Controller.api.formattercontent(item.project_summary) + '</td>'
                        // html += '<td>' + item.chargedep_names + '</td>'
                        html += '<td>' + Controller.api.formattercontent(item.chargedep_names) + '</td>'
                        html += '<td>' + Controller.api.formattercontent(item.project_progress) + '</td>'
                        html += '<td>' + Controller.api.formattercontent(item.project_problem) + '</td>'
                        html += '<td>' + Controller.api.formattercontent(item.project_nextplan) + '</td>'
                        html += '<td>'
                        html += '<a href="leader_approach/editcontent/ids/' + item.id + '" class="btn btn-xs btn-success btn-dialog" data-toggle="tooltip" title=""  data-original-title="编辑"><i class="fa fa-pencil"></i></a>'
                        // html += ' <a href="javascript:;" class="btn btn-xs btn-danger btn-delone" data-toggle="tooltip" title="" data-table-id="table" data-field-index="6" data-row-index="0" data-button-index="2" data-original-title="删除"><i class="fa fa-trash"></i></a>'
                        html += '</td>';
                        html += '</tr>';
                    }

                };
                html += '</table>';

                $detail.html(html)

            }
            Table.api.bindevent(table);


            var table2 = $("#table2");
            // 初始化表格
            table2.bootstrapTable({
                url: 'leader_approach/index' + location.search,
                pk: 'id',
                sortName: 'id',
                singleSelect: true,
                detailView: true,
                toolbar: "#toolbar2",

                columns: [
                    [
                        { checkbox: true },
                        // { field: 'id', title: __('Id') },
                        { field: 'number', title: __('编号'),width:'50px'},
                        // {field: 'leader_ids', title: __('Leader_ids')},
                        { field: 'out_date', title: __('Out_date') },
                        { field: 'leader_names', title: __('Leader_names') },
                        { field: 'out_city', title: __('Out_city') },
                        // {field: 'create_time', title: __('Create_time'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        // {field: 'update_time', title: __('Update_time'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        { field: 'operate', title: __('Operate')}
                        // {
                        //     field: 'check',
                        //     width: "120px",
                        //     title: __('审核'),
                        //     table: table2,
                        //     events: Table.api.events.operate,
                        //     buttons: [
                        //         {
                        //             name: 'check',
                        //             text: '审核',
                        //             title: __('审核'),
                        //             classname: 'btn btn-xs btn-warning  btn-magic btn-dialog',
                        //             icon: 'fa fa-folder-o',
                        //             url: 'leader_approach/checkedit',
                        //         }
                        //     ],
                        //     formatter: Table.api.formatter.buttons
                        // }

                    ]
                ],
                onExpandRow: function(index, row, $detail) {
                    // console.log($detail);
                    InitSubTable1(index, row, $detail);
                }
                // columns: [
                //     [
                //         {checkbox: true},
                //         { field: 'contents.id', title: __('Id') },
                //         {
                //             field: 'check',
                //             width: "120px",
                //             title: __('审核'),
                //             table: table2,
                //             events: Table.api.events.operate,
                //             buttons: [
                //                 {
                //                     name: 'check',
                //                     text: '审核',
                //                     title: __('审核'),
                //                     classname: 'btn btn-xs btn-warning  btn-magic btn-dialog',
                //                     icon: 'fa fa-folder-o',
                //                     url: 'leader_approach/checkedit',
                //                 }
                //             ],
                //             formatter: Table.api.formatter.buttons
                //         },
                //     ]
                // ],

            });
            // 为表格绑定事件
            InitSubTable1 = function(index, row, $detail) {
                // console.log(row.status+"@@@@@@@@@@");
                var html = '';
                html += '<table class="table table-striped table-bordered " style="width:100%" >';
                html += '<tr>';
                // html += '<th  style="text-align:center">序号</th>'
                html += '<th  style="text-align:center">拜访企业</th>'
                html += '<th  style="text-align:center">需推进事项</th>'
                html += '<th  style="text-align:center">责任单位</th>'
                html += '<th  style="text-align:center">工作进展情况</th>'
                html += '<th  style="text-align:center">存在问题</th>'
                html += '<th  style="text-align:center">下步计划</th>'
                html += '<th  style="text-align:center">操作</th>'
                html += '</tr>';
                var numArr = Controller.api.mergeCells(row.contents,'company');
                console.log(row.contents+"@@@@@@@@@@");
                for(var i=0;i<row.contents.length;i++) {
                    var item = row.contents[i];
                    // console.log(value.company)

                    if(item.status==1)
                    {
                        html += '<tr data-index='+i+' >';
                        // let it = numArr.find((v)=>{
                        //     return v.index == i
                        // })
                        // let inx = numArr.findIndex((v)=>{
                        //     return v.index == i
                        // })
                        // if(it)
                        // {
                        //     html += '<td rowspan="'+it.number+'" valign="middle">' + (inx+1) + '</td>'
                        //     html += '<td rowspan="'+it.number+'" valign="middle">' + item.company + '</td>'
                        // }
                        // html += '<td>' + Controller.api.formattercontent(item.id) + '</td>'
                        html += '<td valign="middle">' + Controller.api.formattercontent(item.company) + '</td>'

                        html += '<td valign="middle">' + Controller.api.formattercontent(item.project_summary) + '</td>'
                        html += '<td valign="middle">' + Controller.api.formattercontent(item.chargedep_names) + '</td>'
                        html += '<td valign="middle">' + Controller.api.formattercontent(item.project_progress) + '</td>'
                        html += '<td valign="middle">' + Controller.api.formattercontent(item.project_problem) + '</td>'
                        html += '<td valign="middle">' + Controller.api.formattercontent(item.project_nextplan) + '</td>'
                        html += '<td valign="middle">'
                        // html += '<a href="leader_approach/checkedit/ids/' + item.id + '" class="btn btn-xs btn-success btn-dialog" data-toggle="tooltip" title=""  data-original-title="编辑"><i class="fa fa-pencil"></i></a>'
                        // html += ' <a href="javascript:;" class="btn btn-xs btn-danger btn-delone" data-toggle="tooltip" title="" data-table-id="table" data-field-index="6" data-row-index="0" data-button-index="2" data-original-title="删除"><i class="fa fa-trash"></i></a>'

                        html += '<a href="leader_approach/checkedit/ids/' + item.id + '" class="btn btn-xs btn-warning  btn-magic btn-dialog" title="审核" data-table-id="table2" data-field-index="' + item.id + '" data-row-index="0" data-button-index="0"><i class="fa fa-folder-o"></i> 审核</a>'
                        html += '</td>';
                        html += '</tr>';
                    }

                };
                html += '</table>';

                $detail.html(html)

            }

            // 为表格绑定事件
            Table.api.bindevent(table2);



            $(".toolbar").on('click', '#addcontent', function() {
                var ids = Table.api.selectedids(table);

                var url = 'leader_approach/addcontent/ids/{ids}';
                if (url.indexOf("{ids}") !== -1) {
                    url = Table.api.replaceurl(url, { ids: ids.length > 0 ? ids.join(",") : 0 }, table);
                }
                console.log(url)
                Fast.api.open(url, __('添加内容'), $(this).data() || {});
            });

            $("#btn-import-custom").click(function () {
                var url = 'leader_approach/importleader';
                Fast.api.open(url, __('Import'), {});
            });


        },

        add: function() {
            Controller.api.bindevent();
            var form = $("form[role=form]");
            require(['bootstrap-daterangepicker'], function() {
                var ranges = {};
                // ranges[__('Today')] = [Moment().startOf('day'), Moment().endOf('day')];
                // ranges[__('Yesterday')] = [Moment().subtract(1, 'days').startOf('day'), Moment().subtract(1, 'days').endOf('day')];
                // ranges[__('Last 7 Days')] = [Moment().subtract(6, 'days').startOf('day'), Moment().endOf('day')];
                // ranges[__('Last 30 Days')] = [Moment().subtract(29, 'days').startOf('day'), Moment().endOf('day')];
                // ranges[__('This Month')] = [Moment().startOf('month'), Moment().endOf('month')];
                // ranges[__('Last Month')] = [Moment().subtract(1, 'month').startOf('month'), Moment().subtract(1, 'month').endOf('month')];
                var options = {
                    timePicker: false,
                    autoUpdateInput: false,
                    timePickerSeconds: false,
                    timePicker24Hour: false,
                    autoApply: false,
                    locale: {
                        format: 'YYYY-MM-DD',
                        customRangeLabel: __("Custom Range"),
                        applyLabel: __("Apply"),
                        cancelLabel: __("Clear"),
                    },
                    // ranges: ranges,
                };
                var origincallback = function(start, end) {
                    $(this.element).val(start.format(this.locale.format) + " - " + end.format(this.locale.format));
                    $(this.element).trigger('blur');
                };
                $(".mydatetimerange", form).each(function() {
                    var callback = typeof $(this).data('callback') == 'function' ? $(this).data('callback') : origincallback;
                    $(this).on('apply.daterangepicker', function(ev, picker) {
                        callback.call(picker, picker.startDate, picker.endDate);
                    });
                    $(this).on('cancel.daterangepicker', function(ev, picker) {
                        $(this).val('').trigger('blur');
                    });
                    $(this).daterangepicker($.extend(true, options, $(this).data()), callback);
                });
            });


        },

        edit: function() {
            Controller.api.bindevent();
            var form = $("form[role=form]");
            require(['bootstrap-daterangepicker'], function() {
                var ranges = {};
                var options = {
                    timePicker: false,
                    autoUpdateInput: false,
                    timePickerSeconds: false,
                    timePicker24Hour: false,
                    autoApply: false,
                    locale: {
                        format: 'YYYY-MM-DD',
                        customRangeLabel: __("Custom Range"),
                        applyLabel: __("Apply"),
                        cancelLabel: __("Clear"),
                    },
                    // ranges: ranges,
                };
                var origincallback = function(start, end) {
                    $(this.element).val(start.format(this.locale.format) + " - " + end.format(this.locale.format));
                    $(this.element).trigger('blur');
                };
                $(".mydatetimerange", form).each(function() {
                    var callback = typeof $(this).data('callback') == 'function' ? $(this).data('callback') : origincallback;
                    $(this).on('apply.daterangepicker', function(ev, picker) {
                        callback.call(picker, picker.startDate, picker.endDate);
                    });
                    $(this).on('cancel.daterangepicker', function(ev, picker) {
                        $(this).val('').trigger('blur');
                    });
                    $(this).daterangepicker($.extend(true, options, $(this).data()), callback);
                });
            });

        },
        addcontent: function() {
            Controller.api.bindevent();
        },
        editcontent: function() {
            Controller.api.bindevent();
        },

        importleader:function() {
            Controller.api.bindevent();
        },

        checkedit:function() {
            $(".all_submit").click(function(event) {
                var that = this;
                Layer.confirm(__('确定要通过审核吗?'), {
                    icon: 3,
                    title: '提示'
                }, function (index) {
                    $.ajax({
                        //几个参数需要注意一下
                        type: "POST",//方法类型
                        dataType: "json",//预期服务器返回的数据类型
                        url: "leader_approach/checkedit/ids/"+ Config.ids,
                        success: function (ret) {
                            parent.Toastr.success('审核成功');
                            parent.$(".btn-refresh").trigger("click");
                            var index = parent.Layer.getFrameIndex(window.name);
                            parent.Layer.close(index);
                        },
                        error : function(error) {
                            console.log(error);
                        }
                    });
                    Layer.close(index);
                });

            });
        },

        api: {
            bindevent: function() {
                Form.api.bindevent($("form[role=form]"));
            },
            formattercontent: function(value, width) {
                var width = width != undefined ? (width.match(/^\d+$/) ? width + "px" : this.width) : "250px";
                if (!value)
                    value = '';
                return "<div style='white-space: nowrap; text-overflow:ellipsis; overflow: hidden; max-width:" + width + ";'>" + value + "</div>";
            },

            // columns: function(table,row) {
            //     var pre_columns = [
            //         {checkbox: true},
            //         {field: '', title: __('序号'),operate:false,table: table,width:'40px',formatter:Table.api.formatter.natureorder},
            //         // {field: 'name', title: __('Name'),operate:'like',width:'150px'},
            //         // {field: 'investment_total', title: __('总投资(亿元)'), width:'90px',operate:'BETWEEN',
            //         //     formatter:function(value,row,index) {
            //         //         if(value == -100)
            //         //             return '待定';
            //         //         else
            //         //             return value;
            //         //     }
            //         // }
            //     ];
            //     var operate_columns = [];
            //     var check_columns = [];
            //     var common_columns = [];

            //     var field_columns = pre_columns.concat(common_columns,oper_columns,check_columns);
            //     return [field_columns];
            // },

            mergeCells: function(data, fieldName) {

                    if (data.length == 0) {
                        return;
                    }
                    var numArr = [];
                    var number = 0;
                    var classzhi = 'dan';
                    if (data.length > 1) {
                        for (let i = 0; i < data.length; i++) {
                            if (data[i][fieldName] != '' && data[i][fieldName] != '-') {
                                if (data[i - 1]) {
                                    if (data[i - 1][fieldName] != '' && data[i - 1][fieldName] != '-') {
                                        if (data[i - 1][fieldName] == data[i][fieldName]) {
                                            number++
                                        } else {
                                            number = number + 1
                                            numArr.push({ index: i - number, number: number, pan: '1' })
                                            number = 0
                                        }
                                    }
                                }
                                if (!data[i + 1]) {

                                    number = number
                                    numArr.push({ index: i - number, number: number + 1, pan: '2' })
                                    number = 0
                                } else {
                                    if (data[i + 1][fieldName] == '' || data[i + 1][fieldName] == '-') {
                                        number = number
                                        numArr.push({ index: i - number, number: number + 1, pan: '3' })
                                        number = 0
                                    }
                                }
                            } else {

                                numArr.push({ index: i, number: 1, pan: '4' })
                            }
                        }
                    } else {

                        numArr.push({ index: 0, number: 1, pan: '5' })
                    }
                    return numArr;

            }
        }
    };
    return Controller;
});